<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 4.3.2 or newer
 *
 * @package		CodeIgniter
 * @author		ExpressionEngine Dev Team
 * @copyright	Copyright (c) 2008, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * CodeIgniter String Helpers
 *
 * @package		CodeIgniter
 * @subpackage	Helpers
 * @category	Helpers
 * @author		ExpressionEngine Dev Team
 * @link		http://codeigniter.com/user_guide/helpers/string_helper.html
 */

// ------------------------------------------------------------------------

/**
 * Trim Slashes
 *
 * Removes any leading/traling slashes from a string:
 *
 * /this/that/theother/
 *
 * becomes:
 *
 * this/that/theother
 *
 * @access	public
 * @param	string
 * @return	string
 */	
if ( ! function_exists('trim_slashes'))
{
	function trim_slashes($str)
	{
		return trim($str, '/');
	} 
}
	
// ------------------------------------------------------------------------

/**
 * Strip Slashes
 *
 * Removes slashes contained in a string or in an array
 *
 * @access	public
 * @param	mixed	string or array
 * @return	mixed	string or array
 */	
if ( ! function_exists('strip_slashes'))
{
	function strip_slashes($str)
	{
		if (is_array($str))
		{	
			foreach ($str as $key => $val)
			{
				$str[$key] = strip_slashes($val);
			}
		}
		else
		{
			$str = stripslashes($str);
		}
	
		return $str;
	}
}

// ------------------------------------------------------------------------

/**
 * Strip Quotes
 *
 * Removes single and double quotes from a string
 *
 * @access	public
 * @param	string
 * @return	string
 */	
if ( ! function_exists('strip_quotes'))
{
	function strip_quotes($str)
	{
		return str_replace(array('"', "'"), '', $str);
	}
}

// ------------------------------------------------------------------------

/**
 * Quotes to Entities
 *
 * Converts single and double quotes to entities
 *
 * @access	public
 * @param	string
 * @return	string
 */	
if ( ! function_exists('quotes_to_entities'))
{
	function quotes_to_entities($str,$doubleQuotes=FALSE)
	{
        if ($doubleQuotes == TRUE) {
            $charArray = array("\'","\"","'",'"');
            $replArray = array("&#39;","&quot;","&#39;","&quot;");
        } else {
            $charArray = array("\'","'");
            $replArray = array("&#39;","&#39;");
        }
		return str_replace($charArray, $replArray, $str);
	}
}

if ( ! function_exists('stripTags'))
{
	function stripTags($str)
	{
		return strip_tags($str, '<b><i><em><strong><img><br /><br><p><a>');
	}
}

/**
 * Entities to Quotes
 *
 * Converts single and double quote HTML entities to single and double quotes
 * for inserting into a textfield
 *
 * @access	public
 * @param	string
 * @return	string
 */
if ( ! function_exists('entities_to_quotes'))
{
	function entities_to_quotes($str)
	{
		return str_replace(array("&#39;","&quot;","&#39;","&quot;","&#039;"), array("\'","\"","'",'"',"'"), $str);
	}
}

// ------------------------------------------------------------------------
/**
 * Reduce Double Slashes
 *
 * Converts double slashes in a string to a single slash,
 * except those found in http://
 *
 * http://www.some-site.com//index.php
 *
 * becomes:
 *
 * http://www.some-site.com/index.php
 *
 * @access	public
 * @param	string
 * @return	string
 */	
if ( ! function_exists('reduce_double_slashes'))
{
	function reduce_double_slashes($str)
	{
		return preg_replace("#([^:])//+#", "\\1/", $str);
	}
}
	
// ------------------------------------------------------------------------

/**
 * Reduce Multiples
 *
 * Reduces multiple instances of a particular character.  Example:
 *
 * Fred, Bill,, Joe, Jimmy
 *
 * becomes:
 *
 * Fred, Bill, Joe, Jimmy
 *
 * @access	public
 * @param	string
 * @param	string	the character you wish to reduce
 * @param	bool	TRUE/FALSE - whether to trim the character from the beginning/end
 * @return	string
 */	
if ( ! function_exists('reduce_multiples'))
{
	function reduce_multiples($str, $character = ',', $trim = FALSE)
	{
		$str = preg_replace('#'.preg_quote($character, '#').'{2,}#', $character, $str);

		if ($trim === TRUE)
		{
			$str = trim($str, $character);
		}

		return $str;
	}
}
	
// ------------------------------------------------------------------------

/**
 * Create a Random String
 *
 * Useful for generating passwords or hashes.
 *
 * @access	public
 * @param	string 	type of random string.  Options: alunum, numeric, nozero, unique
 * @param	integer	number of characters
 * @return	string
 */
if ( ! function_exists('random_string'))
{	
	function random_string($type = 'alnum', $len = 8)
	{					
		switch($type)
		{
			case 'alnum'	:
			case 'numeric'	:
			case 'nozero'	:
		
					switch ($type)
					{
						case 'alnum'	:	$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
							break;
						case 'numeric'	:	$pool = '0123456789';
							break;
						case 'nozero'	:	$pool = '123456789';
							break;
					}

					$str = '';
					for ($i=0; $i < $len; $i++)
					{
						$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
					}
					return $str;
			  break;
			case 'unique' : return md5(uniqid(mt_rand()));
			  break;
		}
	}
}

// ------------------------------------------------------------------------

/**
 * Alternator
 *
 * Allows strings to be alternated.  See docs...
 *
 * @access	public
 * @param	string (as many parameters as needed)
 * @return	string
 */	
if ( ! function_exists('alternator'))
{
	function alternator()
	{
		static $i;	

		if (func_num_args() == 0)
		{
			$i = 0;
			return '';
		}
		$args = func_get_args();
		return $args[($i++ % count($args))];
	}
}

// ------------------------------------------------------------------------

/**
 * Repeater function
 *
 * @access	public
 * @param	string
 * @param	integer	number of repeats
 * @return	string
 */	
if ( ! function_exists('repeater'))
{
	function repeater($data, $num = 1)
	{
		return (($num > 0) ? str_repeat($data, $num) : '');
	} 
}

/**
 * cleanString function
 *
 * @access	public
 * @param	string $string string we want to clean.
 * @return	string clean string
 */
function cleanString($string) {
	$string   = stripslashes($string);	
	$patArray  = array('&#039;','&amp;','#','$',' ',Chr(39),Chr(35),Chr(38),'/');
	$replArray = array('','','','','_','','','','_');
	
	$pats = count($patArray);
	
	for($a=0;$a<=($pats-1);$a++) {
		$string = (str_replace($patArray[$a], $replArray[$a], $string));
	} 
		
	$cleanString = $string;
	return $cleanString;
}

function cleanStringBlog($string) {
	$string = trim(ereg_replace("[^A-Za-z0-9 _]", "", $string));
    $string = str_replace(' ','-',$string);
    return $string;
}

function cleanStringTag($string) {
    $string   = trim(stripslashes($string));
	$patArray  = array(',','&','$','#','/','@','!','^','*','(',')','\'','"');
	$replArray = array('','','','','','','','','','','','','');

    $a=0;
    foreach($patArray as $pat) {
        $string = str_replace($patArray[$a], $replArray[$a], $string);
        $a++;
    }
	return $string;
}

function alphaNumOnly($string) {
    if (ereg('[^A-Za-z0-9]', $string)) {
        return FALSE;
    } else {
        return TRUE;
    }
}

if ( ! function_exists('insertLinebreaks')) {
    function insertLinebreaks($string) {
    	$string = str_replace(Chr(10), '<br />', $string);
		$string = str_replace('\r\n', '<br />', $string);
     	$string = str_replace('\n', '<br />', $string);
		return $string;
    }
}

if ( ! function_exists('clearNewlineReturn')) {
    function clearNewlineReturn($string) {
    	$string = str_replace('\r\n', '', $string);
     	$string = str_replace('\n', '', $string);
        $string = str_replace(Chr(10),'', $string);
        $string = str_replace(Chr(13),'', $string);
		return $string;
    }
}

if ( ! function_exists('clearLinebreaks')) {
    function clearLinebreaks($string) {
        $string = str_replace('<br />',Chr(10), $string);
        $string = str_replace('<br>',Chr(10), $string);
        return $string;
    }
}

if ( ! function_exists('fieldToDB')) {
    function fieldToDB(
		$string,
		$escape           =TRUE,
		$linebreak        =FALSE,
		$prepURL          =FALSE,
		$autoLink         =FALSE,
        $quotesToEntities =TRUE,
		$autoLinkNewWindow=TRUE,
        $stripTags        =FALSE ) {
		$CI =& get_instance();
        $convertDoubleQuotes = TRUE;
		
		if ($escape === TRUE) {
			$CI->db->escape($string);
		}
		if ($prepURL === TRUE) {
			$string = prep_url($string);
		}
		if ($linebreak === TRUE) {
			$string = insertLinebreaks($string);
		}
		if ($autoLink === TRUE) {
			$string = auto_link($string,'url',$autoLinkNewWindow);
		}
        if ($quotesToEntities === TRUE) {
            if ($stripTags == TRUE) {
                $convertDoubleQuotes = FALSE;
            }
            $string = quotes_to_entities($string,$convertDoubleQuotes);
        }
        if ($stripTags === TRUE) {
            $string = stripTags($string);
        }
		return $string;
	}
}

if ( ! function_exists('DBToField')) {
	function DBToField($string,$stripTags=FALSE) {
		$CI =& get_instance();

		$string = clearLinebreaks($string);
		$string = entities_to_quotes($string);

        if ($stripTags == TRUE) {
            $string = strip_tags($string);
        }

		return stripslashes($string);
	}
}

/**
 * getNumericPortion function
 *
 * @access	public
 * @param	string $string string from which we want to extract numbers
 * @return	int    $num    number that we were able to extract or false
 */
if ( ! function_exists('getNumericPortion')) {
	function getNumericPortion($string) {
        $num = '';
        for ($index=0;$index<strlen($string);$index++) {
            if(is_numeric($string[$index])) {
                $num .= $string[$index];
            }
        }
        if ($num>0) {
            return $num;
        } else {
            return false;
        }
    }
}

/**
 * format summary and description text properly.
 * Lines must wrap at 75 chars, use \r\n as delimiter, and have a space at the beginning of extra lines
 * @param string $data the data to be formatted
 * @return	the formatted string
 * @TODO Tested with Outlook 2003. Needs testing with other iCalendar apps such as iCal
 */
function formatIcalData($data){
	$data = strip_tags($data);
	$data = htmlentities($data); //convert html entities to chars (&quot; &lrm; etc)
	$data = strtr($data, array("\n" => '\\n', '\\' => '\\\\', ',' => '\\,', ';' => '\\;')); //escape special chars as per RFC 2445 spec
	return rfc2445Fold($data);
}

/**
 * Function to fold (wrap) lines at the RFC2445 specified line length of 75.
 * (c) 2005-2006 Ioannis Papaioannou (pj@moodle.org)
 * Released under the LGPL.
 * See http://bennu.sourceforge.net/ for more information and downloads
 *
 * @author Ioannis Papaioannou
 * @return	string the properly folded value
 */
function rfc2445Fold($string) {
    if(strlen($string) <= 75) {
        return $string;
    }
    $retval = '';
    while(strlen($string) > 75) {
        $retval .= substr($string, 0, 75 - 1) . "\r\n" . ' ';
        $string  = substr($string, 75 - 1);
    }
    $retval .= $string;
    return $retval;
}

/**
 * Function to generate proper GUID, Implemented as per the Network Working Group draft on UUIDs and GUIDs
 * (c) 2005-2006 Ioannis Papaioannou (pj@moodle.org)
 * Released under the LGPL.
 * See http://bennu.sourceforge.net/ for more information and downloads
 *
 * @author Ioannis Papaioannou
 * @return	string the generated UID
 * @TODO This function should be used to generate unique IDs for the mail functionality as well, and should probably be moved there
 */
function generate_guid() {
	// These two octets get special treatment
	$time_hi_and_version       = sprintf('%02x', (1 << 6) + mt_rand(0, 15)); // 0100 plus 4 random bits
	$clock_seq_hi_and_reserved = sprintf('%02x', (1 << 7) + mt_rand(0, 63)); // 10 plus 6 random bits

	// Need another 14 random octects
	$pool = '';
	for($i = 0; $i < 7; ++$i) {
		$pool .= sprintf('%04x', mt_rand(0, 65535));
	}

	// time_low = 4 octets
	$random  = substr($pool, 0, 8).'-';

	// time_mid = 2 octets
	$random .= substr($pool, 8, 4).'-';

	// time_high_and_version = 2 octets
	$random .= $time_hi_and_version.substr($pool, 12, 2).'-';

	// clock_seq_high_and_reserved = 1 octet
	$random .= $clock_seq_hi_and_reserved;

	// clock_seq_low = 1 octet
	$random .= substr($pool, 13, 2).'-';

	// node = 6 octets
	$random .= substr($pool, 14, 12);

	return $random;
}

function twitterReplaceHashTags($string) {
    return preg_replace('/([^\w])\#([\w\-]+)/m','$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>',$string);
}

function replaceURLWithHyperlink($string) {
    return preg_replace('/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/\.]*(\?\S+)?)?)?)/m','<a href="$1" target="_blank">$1</a>',$string);
}

function twitterReplaceMention($string) {
    return preg_replace('/([^\w])\@([\w\-]+)/m','$1@<a href="http://twitter.com/$2" target="_blank">$2</a>',$string);
}

function formatRecurring($recurring) {
    if (!empty($recurring)) {
        $recurringArray = explode('|',$recurring);
        $chunk = $recurringArray[0];
        $days = $recurringArray[1];
        $monthArray = array('01'=>'jan','02'=>'feb','03'=>'mar','04'=>'apr','05'=>'may','06'=>'jun','07'=>'jul','08'=>'aug','09'=>'sep','10'=>'oct','11'=>'nov','12'=>'dec');

        switch ($chunk) {
            case 'day':
                $chunkText = lang('calendar_repeats_day');
                break;
            case 'week':
                $chunkText = lang('calendar_repeats_week');
                break;
            case 'month':
                $chunkText = lang('calendar_repeats_month');
                break;
            case 'year':
                $chunkText = lang('calendar_repeats_year');
                break;
        }

        $daysArray = explode(',',$days);
        $dayString = '';
        foreach($daysArray as $day) {
            if (!empty($day)) {
                if ($chunk == 'year') {
                    $dateArray = explode('-',$day);
                    $month = $monthArray[$dateArray[0]];
                    $monthName = lang('cal_'.$month);
                    $dayString .= $monthName.' '.$day[1].', ';
                } else {
                    $dayString .= $day.', ';
                }
            }
        }
        $dayString = substr($dayString,0,-2);
        return $chunkText.' ('.$dayString.')';
    } else {
        return false;
    }
}

/* End of file string_helper.php */
/* Location: ./system/helpers/string_helper.php */